package com.chexiehui.jc.base;


import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.blankj.utilcode.util.StringUtils;
import com.trello.rxlifecycle2.components.support.RxFragment;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * base fragment
 * Created by SongJun on 2016/11/28.
 */
public abstract class BaseFragment extends RxFragment {

    protected BaseActivity mActivity;
    private Unbinder unbinder;
    protected SVProgressHUD mSVProgressHUD;
    private View mView;
    protected boolean isTablet;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        mActivity = (BaseActivity) getActivity();
        isTablet = isTablet();
        beforeSetView();
        if (mView != null) {
            ViewGroup parent = (ViewGroup) mView.getParent();
            if (parent != null) {
                parent.removeView(mView);
            }

        } else {
            mView = inflater.inflate(getLayoutId(), container, false);
        }
        unbinder = ButterKnife.bind(this, mView);
        if (isRegisterEventBus()) {
            EventBus.getDefault().register(this);
        }
        mSVProgressHUD = new SVProgressHUD(mActivity);
        return mView;
    }

    protected abstract int getLayoutId();

    protected void beforeSetView() {
    }

    protected void afterSetView() {
    }

    protected void initTitleView(Bundle savedInstanceState) {
    }

    protected void initView(Bundle savedInstanceState) {
    }

    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return false;
    }

    public BaseActivity getMyActivity() {
        return (BaseActivity) getActivity();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initTitleView(savedInstanceState);
        initView(savedInstanceState);
        afterSetView();
    }

    protected View getRootView(){
        return mView;
    }

    @Override
    public void onDestroy() {
        if (mSVProgressHUD != null) {
            if (mSVProgressHUD.isShowing()) mSVProgressHUD.dismiss();
        }
        if (isRegisterEventBus() && EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
        unbinder = null;
        mActivity = null;
        mView = null;
        mSVProgressHUD = null;
        mView = null;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public void showToast(int resId) {
        showToast(getResources().getString(resId));
    }

    public void showToast(String text) {
        if (mActivity == null) return;
        mActivity.showToast(text);
    }


    public void showDefault() {//
        if (mSVProgressHUD != null) {
            mSVProgressHUD.showWithMaskType(SVProgressHUD.SVProgressHUDMaskType.Black);
        }
    }

    public void showLoading(String loadding) {//1
        mSVProgressHUD.showWithStatus(StringUtils.isTrimEmpty(loadding) ? "加载中..." : loadding, SVProgressHUD.SVProgressHUDMaskType.Black);
    }

    public void showWarning(String warning) {//2
        if (mSVProgressHUD != null) {
            mSVProgressHUD.showInfoWithStatus(StringUtils.isTrimEmpty(warning) ? "警告" : warning, SVProgressHUD.SVProgressHUDMaskType.Black);
        }
    }

    public void showSuccess(String success) {//3
        mSVProgressHUD.showSuccessWithStatus(StringUtils.isTrimEmpty(success) ? "成功!" : success, SVProgressHUD.SVProgressHUDMaskType.Black);
    }

    public void showError(String error) {//4
        if (mSVProgressHUD != null) {
            mSVProgressHUD.showErrorWithStatus(StringUtils.isTrimEmpty(error) ? "出错啦～" : error, SVProgressHUD.SVProgressHUDMaskType.Black);
        }
    }

    public void showProgress(int progress) {//5
        if (mSVProgressHUD != null) {
            mSVProgressHUD.getProgressBar().setProgress(0);
            mSVProgressHUD.showWithProgress("进度 " + 0 + "%", SVProgressHUD.SVProgressHUDMaskType.Black);
        }
    }

    public void setProgressValue(int progress) {
        if (mSVProgressHUD != null) {
            if (mSVProgressHUD.getProgressBar().getMax() != mSVProgressHUD.getProgressBar().getProgress()) {
                mSVProgressHUD.getProgressBar().setProgress(progress);
                mSVProgressHUD.setText("进度 " + progress + "%");
            }
        }
    }

    public void hide() {
        if (mSVProgressHUD != null && mSVProgressHUD.isShowing()) {
            mSVProgressHUD.dismiss();
        }
    }

    public void removeCallBack(ApiCallback callback) {

    }

    public Context getMContext() {
        return mActivity;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public boolean isLogin() {
        return mActivity.isLogin();
    }

    public String getUserToken() {
        return mActivity.getUserToken();
    }

    public String getUserId() {
        return mActivity.getUserId();
    }

    public boolean isFinish() {
        boolean a = mActivity == null || mActivity.isFinishing();
        if (Build.VERSION.SDK_INT < 17) {
            return a;
        } else {
            return a || mActivity.isDestroyed() || mActivity.getFragmentManager().isDestroyed();
        }
    }

    public String getStringSource(int res) {
        return getString(res);
    }

    public void gotoLogin() {
        if (getMyActivity() != null)
            getMyActivity().gotoLogin();
    }

    public void startActivity(Class<? extends Activity> activity) {
        if (mActivity != null) {
            mActivity.startActivity(activity, null);
        }
    }

    public void startActivity(Class<? extends Activity> activity, Bundle bundle) {
        if (mActivity != null) {
            mActivity.startActivity(activity, bundle);
        }
    }

    public void startActivityAnimBottom(Class<? extends Activity> activity) {
        if (mActivity != null) {
            mActivity.startActivityAnimBottom(activity);
        }
    }

    public void startActivityAnimBottom(Class<? extends Activity> activity, Bundle bundle) {
        if (mActivity != null) {
            mActivity.startActivityAnimBottom(activity, bundle);
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (isCancelRequestOnClickBack()) {
                if (mSVProgressHUD != null && mSVProgressHUD.isShowing()) {
                    mSVProgressHUD.dismiss();
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 点击返回取消正在请求的对话框
     *
     * @return
     */
    public boolean isCancelRequestOnClickBack() {
        return true;
    }

    public boolean isTablet() {
        return mActivity != null && mActivity.isTablet();
    }
}
